from django.shortcuts import render

# Create your views here.
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django.utils.safestring import mark_safe
from utils import pagination
from django import views
from django.utils.decorators import method_decorator
from django.contrib import auth
from functools import wraps

from cmdb import models
import json


def login(request):
    # 包含用户提交的所有信息
    # 获取用户提交方法
    # print(request.method)
    error_msg = ""
    if request.method == "POST":
        # 获取用户通过POST提交过来的数据
        user = request.POST.get('user', None)
        pwd = request.POST.get('pwd', None)
        if user == 'root' and pwd == "123":
            # 去跳转到
            return redirect('/home')
        else:
            # 用户密码不配
            error_msg = "用户名或密码错误"
    return render(request, 'login.html', {'error_msg': error_msg})


USER_LIST = [
    {'id': 1, 'username': 'alex', 'email': 'abc', "gender": '男'},
    {'id': 2, 'username': 'luci', 'email': 'song link', "gender": '男'},
    {"id": 3, 'username': 'seven', 'email': 'good dog', "gender": '男'},
]

for index in range(10):
    temp = {'id': index, 'username': 'alex' + str(index), 'email': '123@qq.com', 'gender': '女'}
    USER_LIST.append(temp)


def home(request):
    print(request.GET.get('nid'))

    if request.method == "POST":
        # 获取用户提交的数据 POST请求中
        u = request.POST.get('username')
        e = request.POST.get('email')
        g = request.POST.get('gender')
        temps = {'username': u, 'email': e, "gender": g}
        USER_LIST.append(temps)
    return render(request, 'test/home.html', {'user_list': USER_LIST})


# def detail(request):
#     nid = request.GET.get('nid')
#     print(nid)
#     nid = int(nid)
#     detail_info = USER_LIST[nid]
#     return render(request, 'detail.html', {'detail_info':  detail_info})


def detail(request, nid):
    detail_info = USER_LIST[int(nid)]
    return render(request, 'detail.html', {'detail_info': detail_info})


def orm(request):
    """数据库增加数据"""
    # models.UserType.objects.create(
    #     name='root',
    # )

    obj = models.UserType(name='li si')
    obj.save()

    return HttpResponse('orm')


def sel(request):
    """数据库查询"""
    # result = models.UserType.objects.all()  # 查询所有
    result = models.UserType.objects.filter(name='root')  # 条件查询
    for row in result:
        print(row.name, row.id)
    return HttpResponse('sel')


def dell(request):
    """删除数据"""
    models.UserType.objects.filter(name='root').delete()  # 删除所有
    return HttpResponse('dell')


def upd(request):
    """更新数据"""
    models.UserType.objects.filter(id=1).update(name='li si si')  # 删除所有
    return HttpResponse('upd')


def business(request):
    """查询demo"""
    v = models.Business.objects.all()
    # QuerySet 内部元素是对象
    # [obj(id,caption,code)...]

    v2 = models.Business.objects.all().values('id', 'caption')
    # QuerySet 内部元素是字典
    # [{'id':1, 'caption': '运维部'}...]

    v3 = models.Business.objects.all().values_list('id', 'caption')
    # QuerySet 内部元素是元组
    # [(1,运维部),(2,开发板)...]
    return render(request, 'business.html', {'v': v, 'v2': v2, 'v3': v3})


"""
models.Business.objects.get(id=1)  # 获取到一个对象，如果不存在就报错
models.Business.objects.filter(id=1).first()  # 对象或者None
"""


# def host(request):
#     """获取主机"""
#     v1 = models.Host.objects.filter(nid__gt=0)
#     for row in v1:
#         print(row.nid, row.hostname, row.ip, row.port, row.b_id, row.b.caption)
#     # return HttpResponse('host')
#     # b__caption 跨表查询
#     v2 = models.Host.objects.filter(nid__gt=0).values('nid', 'hostname', 'b_id', 'b__caption')
#     print(v2)
#     return render(request, 'host.html', {'v1': v1})
def host(request):
    """获取主机"""
    if request.method == 'GET':
        b_list = models.Business.objects.all()
        v1 = models.Host.objects.filter(nid__gt=0)
        return render(request, 'host.html', {'v1': v1, 'b_list': b_list})
    elif request.method == 'POST':
        h = request.POST.get('hostname')
        i = request.POST.get('ip')
        p = request.POST.get('port')
        b = request.POST.get('b_id')
        # models.Host.objects.create(
        #     hostname=h,
        #     ip=i,
        #     port=p,
        #     b=models.Business.objects.get(id=b)
        # )
        models.Host.objects.create(
            hostname=h,
            ip=i,
            port=p,
            b_id=b
        )
        return redirect('/cmdb/host')


def test_ajax(request):
    ret = {'status': True, 'error': None, 'data': None}
    # print(request.method, request.GET.get('user'), request.GET.get('pwd'), sep='\t')
    # return HttpResponse('cheng gong')
    # noinspection PyBroadException
    try:
        h = request.POST.get('hostname')
        i = request.POST.get('ip')
        p = request.POST.get('port')
        b = request.POST.get('b_id')
        if h and len(h) > 5:
            models.Host.objects.create(
                hostname=h,
                ip=i,
                port=p,
                b_id=b
            )
        else:
            ret['status'] = False
            ret['error'] = '输入内容太短了'
    except Exception as e:
        ret['status'] = False
        ret['error'] = e
    return HttpResponse(json.dumps(ret))


def app(request):
    if request.method == 'GET':
        app_list = models.Application.objects.all()
        host_list = models.Host.objects.all()
        return render(request, 'app.html', {'app_list': app_list, 'host_list': host_list})
    elif request.method == 'POST':
        app_name = request.POST.get('app_name')
        host_list = request.POST.getlist('host_list')

        obj = models.Application.objects.create(name=app_name)
        obj.r.add(*host_list)

        return redirect('/cmdb/app')


def add_submit_ajax(request):
    ret = {'status': True, 'error': None, 'data': None}
    app_name = request.POST.get('app_name')
    host_list = request.POST.getlist('host_list')
    obj = models.Application.objects.create(name=app_name)
    obj.r.add(*host_list)

    return HttpResponse(json.dumps(ret))


def tpl(request):
    user_list1 = [1, 2, 3, 46]
    return render(request, 'tpl.html', {'u': user_list1})


def tpl2(request):
    name = 'ABCDEFGHiabcdefg'
    return render(request, 'tpl2.html', {'name': name})


def user_list(request):
    li = []
    for w in range(100):
        li.append(w)
    return render(request, 'user_list.html', {'li': li})


LIST = []
for q in range(100):
    LIST.append(q)


def user_list2(request):
    current_page = request.GET.get('p', 1)
    current_page = int(current_page)
    per_page_count = 10
    start = (current_page-1) * per_page_count
    end = current_page * 10
    data = LIST[start:end]
    all_count = len(LIST)
    total_count, y = divmod(all_count, 10)
    if y:
        total_count += 1
    page_list = []
    pager_num = 5
    # 当前页
    if total_count < pager_num:
        start_index = 1
        end_index = total_count + 1
    else:
        if current_page <= (pager_num+1)/2:
            start_index = 1
            end_index = pager_num + 1
        else:
            start_index = current_page - (pager_num-1)/2
            end_index = current_page + (pager_num+1)/2
            if (current_page + (pager_num-1)/2) > total_count:
                end_index = total_count + 1
                start_index = total_count - pager_num + 1
    if current_page == 1:
        prev = '<a class="page" href="#">上一页</a>'
    else:
        prev = '<a class="page" href="/cmdb/user_list2?p=%s">上一页</a>' % (current_page-1,)
    page_list.append(prev)
    for i in range(int(start_index), int(end_index)):
        if i == current_page:
            temps = '<a class="page active" href="/cmdb/user_list2?p=%s">%s</a>' % (i, i)
        else:
            temps = '<a class="page" href="/cmdb/user_list2?p=%s">%s</a>' % (i, i)
        page_list.append(temps)
    if current_page == total_count:
        nex = '<a class="page" href="javascript:void(0);">下一页</a>'
    else:
        nex = '<a class="page" href="/cmdb/user_list2?p=%s">下一页</a>' % (current_page+1,)
    page_list.append(nex)
    jump = """
    <label>
        <input type='text'/><a onclick='jumpTo(this, "/cmdb/user_list2?p=");'>Go</a>
    </label>
    <script>
        function jumpTo(ths,base){
            const val = ths.previousSibling.value;
            location.href = base + val;
        }
    </script>
    """
    page_list.append(jump)
    page_str = "".join(page_list)
    page_str = mark_safe(page_str)
    return render(request, 'user_list.html', {'li': data, 'page_str': page_str})


def user_list3(request):
    current_page = request.GET.get('p', 1)
    current_page = int(current_page)
    val = request.COOKIES.get('per_page_count')
    print(val)
    val = int(val)
    page_obj = pagination.Page(current_page, len(LIST), val)
    # page_obj = pagination.Page(current_page, len(LIST))
    data = LIST[page_obj.start:page_obj.end]
    page_str = page_obj.page_srt('/cmdb/user_list3')
    return render(request, 'user_list.html', {'li': data, 'page_str': page_str})


# cookie
user_info = {
    'liming': {'pwd': '123456'},
    'lili': {'pwd': '123456'},
}


def auth(func):
    def inner(request, *args, **kwargs):
        v = request.COOKIES.get('username111')
        if not v:
            return redirect('/cmdb/login2')
        return func(request, *args, **kwargs)
    return inner


def login2(request):
    if request.method == "GET":
        return render(request, 'login2.html')
    if request.method == "POST":
        u = request.POST.get('user')
        p = request.POST.get('pwd')
        dic = user_info.get(u)
        if not dic:
            return render(request, 'login2.html')
        if dic['pwd'] == p:
            res = redirect('/cmdb/index')
            res.set_cookie('username111', u)
            return res
        else:
            return render(request, 'login2.html')


@auth
def index(request):
    v = request.COOKIES.get('username111')
    # if not v:
    #     return redirect('/cmdb/login2')
    return render(request, 'index.html', {'current_user': v})


@method_decorator(auth, name='dispatch')
class Order(views.View):
    def get(self, request):
        v = request.COOKIES.get('username111')
        return render(request, 'index.html', {'current_user': v})

    def post(self, request):
        v = request.COOKIES.get('username111')
        return render(request, 'index.html', {'current_user': v})


# 基于session登陆的实现
# python manage.py makemigrations
# python manage.py migrate
def login3(request):
    if request.method == "GET":
        return render(request, 'login3.html')
    elif request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user == 'root' and pwd == '123':
            request.session['username'] = user
            request.session['is_login'] = True
            return redirect('/cmdb/index2')
        else:
            return render(request, 'login3.html')


def index2(request):
    if request.session.get('is_login', None):
        return render(request, 'index2.html', {'username': request.session['username']})
    else:
        return HttpResponse('out')


def logout(request):
    request.session.clear()
    return redirect('/cmdb/login3')


# cache
from django.views.decorators.cache import cache_page


# @cache_page(60*15)   # 对函数添加缓存 60秒*15，即15分钟
def cache(request):
    import time
    ctime = time.time()
    return render(request, 'cache.html', {'ctime': ctime})


# ############################### Form ##################################
from django import forms
from django.forms import widgets
from django.forms import fields


class FM(forms.Form):
    # 字段本身只做验证
    user = fields.CharField(
        error_messages={'required': '用户名不能为空'},
        widget=widgets.Textarea(attrs={'class': 'c1'}),  # 自定义样式定义
        label="用户名",
        initial='你好啊',
    )
    pwd = fields.CharField(
        max_length=12,
        min_length=6,
        error_messages={'required': '密码不能为空', 'min_length': '密码长度不能小于6', 'max_length': '密码长度不能大于12'},
        widget=widgets.PasswordInput(attrs={'class': 'c2'})
    )
    email = fields.EmailField(
        error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'}
    )
    f = fields.FileField()
    p = fields.FilePathField(path='cmdb')
    city = fields.ChoiceField(
        choices=[(0, '上海'), (1, '广州'), (2, '北京')]
    )
    city2 = fields.MultipleChoiceField(
        choices=[(0, '上海'), (1, '广州'), (2, '北京')]
    )


def fm(request):
    """
    Form 验证组件的使用
    :param request:
    :return:
    """
    if request.method == "GET":
        # 从数据库中把数据获取到
        dic = {
            'user': 'r1',
            'pwd': '123456',
            'city': 1,
            'city2': [1, 2]
        }
        obj = FM(initial=dic)
        return render(request, 'fm.html', {'obj': obj})
    elif request.method == 'POST':
        # 获取用户所有数据
        # 每条数据请求的验证
        # 成功：获取所有的正确信息
        # 失败：显示错误信息
        obj = FM(request.POST)
        r1 = obj.is_valid()
        if r1:
            print(obj.cleaned_data)
            # models.UserInfo.objects.create(**obj.cleaned_data) # 注册功能实现
        else:
            print(obj.errors.as_json())
            return render(request, 'fm.html', {'obj': obj})
        return redirect('/cmdb/fm')


def upload(request):
    """
    上传功能的实现
    :param request:
    :return:
    """
    if request.method == "GET":
        return render(request, 'upload.html')
    elif request.method == "POST":
        return redirect('/cmdb/index2')


def upload_file(request):
    username = request.POST.get('username')
    uploads = request.FILES.get('upload')
    print(username, uploads)
    import os
    img_path = os.path.join('static/imgs/', uploads.name)
    with open(img_path, 'wb') as f:
        for item in uploads.chunks():
            f.write(item)
    ret = {'code': True, 'data': img_path}
    return HttpResponse(json.dumps(ret))


def check_login(f):
    """
    登陆校验装饰器
    :param f:
    :return:
    """
    @wraps(f)  # 装饰器修复技术
    def inner(request, *args, **kwargs):
        if request.session.get('is_login') == '1':
            return f(request, *args, **kwargs)
        else:
            return redirect('/cmdb/auth')
    return inner


def auth(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = models.User.objects.filter(username=username, password=password)
        if user:
            request.session['is_login'] = '1'
            # request.session['username'] = username
            request.session['user_id'] = user[0].id
            return redirect('/cmdb/index3')

    return render(request, 'auth.html')


@check_login
def index3(request):
    user_id = request.session.get('user_id')
    user_obj = models.User.objects.filter(id=user_id)
    if user_obj:
        return render(request, 'index3.html', {'user': user_obj[0]})
    else:
        return render(request, 'index3.html', {'user': "匿名用户"})
